﻿using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;

namespace DFGK_WMS.Common.WebSocketModule;

/// <summary>
/// WebSocketConnectManager 类用于管理所有 WebSocket 连接
/// </summary>
public class WebSocketConnectManager
{
    /// <summary>
    /// 构造
    /// </summary>
    /// <param name="logger"></param>
    public WebSocketConnectManager(ILogger<WebSocketConnectManager> logger)
    {
        this.logger = logger;
    }

    private ConcurrentDictionary<string, WebSocket> _sockets = new();
    private readonly ILogger<WebSocketConnectManager> logger;

    /// <summary>
    /// 添加新的 WebSocket 连接
    /// </summary>
    /// <param name="id"></param>
    /// <param name="socket"></param>
    public void AddSocket(string id, WebSocket socket)
    {
        _sockets.TryAdd(id, socket);
        logger.LogInformation($"ip地址为[{id}]的客户端连接WebSocket成功");
    }

    /// <summary>
    /// 根据id移除 WebSocket 连接
    /// </summary>
    /// <param name="id"></param>
    public void RemoveSocket(string id)
    {
        _sockets.TryRemove(id, out _);
        logger.LogInformation($"ip地址{id}的WebSocket的连接断开");
    }

    /// <summary>
    /// 根据id获取 WebSocket 连接
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public WebSocket? GetSocketById(string id)
    {
        if (_sockets.TryGetValue(id, out var socket)) return socket;
        return null;
    }


    /// <summary>
    /// 获取所有 WebSocket 连接
    /// </summary>
    /// <returns></returns>
    public ConcurrentDictionary<string, WebSocket> GetAllSockets()
    {
        return _sockets;
    }

    private async Task SendMessage(WebSocket socket, string message)
    {
        try
        {
            var buffer = Encoding.UTF8.GetBytes(message);
            await socket.SendAsync(new ArraySegment<byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true,
                CancellationToken.None);
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    /// <summary>
    /// 示例：向所有客户端发送消息
    /// </summary>
    /// <param name="message"></param>
    /// <returns></returns>
    public async Task SendMsgToAllClients(string message)
    {
        var sockets = GetAllSockets();
        foreach (var socket in sockets)
        {
            if (socket.Value.State != WebSocketState.Open)
            {
                RemoveSocket(socket.Key);
                continue;
            }

            try
            {
                await SendMessage(socket.Value, message);
            }
            catch (Exception)
            {
                throw;
            }
        }
    }

    /// <summary>
    /// 发送消息给特定客户端
    /// </summary>
    /// <param name="clientId">客户id</param>
    /// <param name="message">发送的消息</param>
    /// <returns></returns>
    public async Task SendMsgToClient(string clientId, string message)
    {
        var socket = GetSocketById(clientId);
        if (socket != null)
            try
            {
                await SendMessage(socket, message);
            }
            catch (Exception)
            {
                throw;
            }
    }
}